package com.luge.lib_base.ktx

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.luge.lib_base.mvvm.vm.BaseViewModel
import com.luge.lib_base.net.BaseResponse
import com.luge.lib_base.net.NetExeceptionHandle
import kotlinx.coroutines.launch

fun<T> BaseResponse<T>.dataChange(
    loadState:MutableLiveData<State>,
    key:String = ""
):T{
    return when(errorCode){
        0 -> {
            if(data is List<*>){
                if((data as List<*>).isEmpty()){
                    loadState.value = State(StateType.EMPTY,key)
                }else{
                    loadState.value = State(StateType.SUCCESS,key)
                }
            }else{
                loadState.value = State(StateType.SUCCESS,key)
            }
            data
        }

        else -> {
            loadState.postValue(State(StateType.ERROR,key, message = errMsg))
            data
        }
    }
}

fun BaseViewModel.request(
    block:suspend ()->Unit,
    loadState: MutableLiveData<State>,
    url:String = ""
){
    viewModelScope.launch {
        runCatching {
            block()
        }.onSuccess {  }.onFailure {
            NetExeceptionHandle.handleException(it,loadState,url)
        }
    }
}

